<?php


namespace app\controller\partner;


use app\BaseController;
use app\common\ErrorCode;
use app\common\exception\ApiException;
use app\common\SmsCode;

use app\model\article\ArticleModel;
use app\model\config\RegionModel;
use app\model\partner\EscortMenuOrderModel;
use app\model\partner\EscortMenuReserveOrderModel;
use app\model\partner\FeedbackModel;
use app\model\partner\UserPartnerModel;
use app\model\user\PartnerMoneyRecordModel;
use app\model\user\PartnerWithdrawRecordModel;
use app\model\user\UserCourseModel;
use app\model\user\UserModel;
use app\service\user\PartnerMoneyRecordService;
use app\service\user\UserPartnerService;
use app\service\utils\SmsService;
use app\service\utils\WeiXinOfficialService;
use app\service\utils\WeiXinPayService;
use app\service\utils\WeiXinService;
use app\validate\user\PartnerLoginValidate;
use think\facade\Cache;
use think\facade\Db;

class UserController extends BaseController
{
    /**
     * 登录
     * @return \think\response\Json
     */
    public function login()
    {
        try {
            $data = $this->request->only(['mobile', 'sms_code'], 'param', 'trim');

            Validate(PartnerLoginValidate::class)->check($data);

            // 使用模型查询用户信息
            $userInfo = UserPartnerModel::where('mobile', $data['mobile'])->find();

            if (!$userInfo) {
                throw new ApiException('用户不存在');
            }
            if ($userInfo['status'] == 0) {
                throw new ApiException('账号被冻结');
            }
            SmsService::verifySms($data['mobile'], $data['sms_code'], SmsCode::APP_LOGIN);

            // 更新用户登录信息和生成token
            $token = random(150, 'all');
            $info = [
                'token' => $token,
                'token_valid_time' => time() + 86400,
            ];
            $userInfo->save($info);
            return $this->success(['token' => $token, 'is_scope' => $userInfo['openid'] ? 0 : 1]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function getUserInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $result = [
                'id' => $userInfo['id'],
                'mobile' => $userInfo['mobile'],
                'username' => $userInfo['username'],
                'avatar' => $userInfo['avatar'],
                'money' => $userInfo['money'],
                'age' => $userInfo['age'],
                'drive_age' => $userInfo['drive_age'],
                'city' => $userInfo['city'],
                'city_name' => RegionModel::where('id', $userInfo['city'])->value('name'),
                'shap' => $userInfo['shap'],
                'openid' => $userInfo['openid'],
                'user_type' => $userInfo['user_type'],
                'ratio' => $userInfo['ratio'],
                'type' => $userInfo['type'],
            ];
            // 今日时间
            $startTime = strtotime(date('Y-m-d'));
            // 今日接单
            $todayOrderList = EscortMenuReserveOrderModel::where('coach_user_id', $userInfo['id'])
                ->where('accept_time', '>=', $startTime)
                ->select()
                ->toArray();
            $result['today_accept_order_count'] = count($todayOrderList);
            // 今日收入
            $result['today_accept_order_income'] = PartnerMoneyRecordModel::where('user_id', $userInfo['id'])
                ->where('create_time', '>=', $startTime)
                ->where('type', '<', 100)
                ->count('amount');

            // 上月收入
            $firstDayOfLastMonth = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
            $lastDayOfLastMonth = strtotime(date('Y-m-t 23:59:59', strtotime('-1 month')));
            $result['last_month_income'] = PartnerMoneyRecordModel::where('user_id', $userInfo['id'])
                ->where('create_time', '>=', $firstDayOfLastMonth)
                ->where('create_time', '<', $lastDayOfLastMonth)
                ->where('type', '<', 100)
                ->sum('amount');
            // 本月收入
            $thisMonthStart = strtotime(date('Y-m-01 00:00:00'));
            $result['this_month_income'] = PartnerMoneyRecordModel::where('user_id', $userInfo['id'])
                ->where('create_time', '>=', $thisMonthStart)
                ->where('type', '<', 100)
                ->sum('amount');
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 转化率
     * @return \think\response\Json
     */
    public function getConversionRatio()
    {
        try {
            // 计算教练的转化率
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            $userPartnerService = new UserPartnerService();
            $ratioInfo = $userPartnerService->calculatePartnerTurnRatio($userId);
            $ratioInfo['ratio'] = $userInfo['ratio'];
            return $this->success($ratioInfo);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 问题反馈
     * @return \think\response\Json
     */
    public function feedback()
    {
        try {
            $userId = $this->request->middleware('userId');
            $img = $this->request->param('img', '', 'trim');
            $content = $this->request->param('content', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            $model = new FeedbackModel();
            $model->user_id = $userId;
            $model->content = $content;
            $model->image = $img;
            $model->mobile = $mobile;
            $model->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 设置用户信息
     * @return \think\response\Json
     */
    public function setUserInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $flag = 0;
            $avatar = $this->request->param('avatar', '', 'trim');
            if ($avatar) {
                $userInfo->avatar = $avatar;
                $flag = 1;
            }
            $age = $this->request->param('age', '', 'trim');
            if ($age) {
                $userInfo->age = $age;
                $flag = 1;
            }
            $driveAge = $this->request->param('drive_age', '', 'trim');
            if ($driveAge) {
                $userInfo->drive_age = $driveAge;
                $flag = 1;
            }
            $city = $this->request->param('city', '', 'trim');
            if ($city) {
                $userInfo->city = $city;
                $flag = 1;
            }
            $shape = $this->request->param('shape', '', 'trim');
            if ($shape) {
                $userInfo->shape = $shape;
                $flag = 1;
            }
            if ($flag) {
                $userInfo->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 账号注销
     * @return \think\response\Json
     */
    public function writeOff()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $code = $this->request->param('sms_code', '', '');
            $mobile = $userInfo['mobile'];
            SmsService::verifySms($mobile, $code, SmsCode::WRITE_OFF);
            $userInfo->token = '';
            $userInfo->save();

            $userInfo->delete();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 学习列表
     * @return \think\response\Json
     */
    public function studyList()
    {
        try {
            $list = UserCourseModel::order('sort', 'asc')->where('type', 1)->field('id,title')->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 学习内容
     * @return \think\response\Json
     */
    public function studyInfo()
    {
        try {
            $id = $this->request->param('id');
            $info = UserCourseModel::find($id);
            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 微信授权
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function wxScope()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');

            $code = $this->request->param('code', '', 'trim');

            $weiXinOfficialService = new WeiXinOfficialService();
            $user = $weiXinOfficialService->wxAuth($code);

            $userInfo->openid = $user->getId();
            $userInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 提现
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function withdraw()
    {
        Db::startTrans();
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');

            $amount = $this->request->param('amount', '', 'trim');
            $type = $this->request->param('type', 0, 'trim');
            $content = $this->request->param('content', '', 'trim');
            $day = date('j');
            if (!in_array($day, [6, 16, 26])) {
                throw new ApiException('每月6号，16号，26号才能提现');
            }
            if ($type == 2 && !$content) {
                throw new ApiException('请填写真实姓名');
            }

            if ($amount <= 0) {
                throw new ApiException('提现金额错误');
            }
            if (!$type) {
                throw new ApiException('请选择提现方式');
            }

            if ($type == 1 && !$content) {
                throw new ApiException('请填写支付宝账号');
            }
            $openId = $userInfo['openid'];
            if ($type == 2 && !$openId) {
                throw new ApiException('用户未授权', ErrorCode::SCOPE_LOGIN);
            }
            $userInfo = UserPartnerModel::lock('lock in share mode')->where('id', $userId)->find();
            $before = $userInfo['money'];
            if ($before < $amount) {
                throw new ApiException('余额不足');
            }

            $orderSn = createOrderSn('partner_withdraw_record', 'order_sn', 'TX');

            $partnerWithdrawRecordModel = new PartnerWithdrawRecordModel();
            $partnerWithdrawRecordModel->user_id = $userId;
            $partnerWithdrawRecordModel->before = $before;
            $partnerWithdrawRecordModel->money = $amount;
            $partnerWithdrawRecordModel->after = bcsub($before, $amount, 2);
            $partnerWithdrawRecordModel->order_sn = $orderSn;
            $partnerWithdrawRecordModel->type = $type;
            $partnerWithdrawRecordModel->content = $content;
//            if ($type == 2) {
//                $partnerWithdrawRecordModel->status = 1;
//            }
            $partnerWithdrawRecordModel->save();

            $partnerMoneyRecordService = new PartnerMoneyRecordService();
            $type = PartnerMoneyRecordService::WITHDRAW;
            $title = $partnerMoneyRecordService->getTypeText($type);
            $partnerMoneyRecordService->createLog($title, $userId, $type, $amount, 0, $orderSn);

//            if ($type == 2 && env('app_environment') == 'pro') {
//                $weiXinPayService = new WeiXinPayService();
//                $weiXinPayService->toBalance($orderSn, $openId, $content, intval($amount * 100), '陪驾教练提现');
//            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 钱包明细
     * @return \think\response\Json
     */
    public function getMoneyRecord()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');

            $list = PartnerMoneyRecordModel::where('user_id', $userInfo['id'])
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success(['money' => $userInfo['money'], 'list' => $list]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 分享二维码
     * @return \think\response\Json
     */
    public function getUserQrcode()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            if (!$userInfo['qrcode']) {
                $weiXinService = new WeiXinService();
                $path = $weiXinService->getCoachQrcode('/pages/tabbar/my?type=2&scene=' . $userId, $userId);
                $userInfo->qrcode = $path;
                $userInfo->save();
            } else {
                $path = $userInfo['qrcode'];
            }
            return $this->success(['qrcode' => $path, 'url' => '']);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}